package com.ztil.properties;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Properties;

/**
 * @author Mr.zyl
 */
public class PropertiesUtils {
	public static void main(String[] args) throws IOException {
	}

	/**
	 * @author Mr.zyl
	 * @param prop		键值
	 * @param fileUrl	文件绝对路径
	 * @param comments	注释
	 * @param encode	编码格式
	 * @throws IOException 
	 */
	public static void saveOrUpdate(Properties prop, String fileUrl, String comments, String encode)
			throws IOException {
		File file = new File(fileUrl);
		if (!file.exists()) {
			file.createNewFile();
		} else {
			Properties oldprop = new Properties();
			try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileUrl), "utf-8"))) {
				oldprop.load(br);
			}
			prop.putAll(oldprop);
		}
		try (FileOutputStream fos = new FileOutputStream(file);
				BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"))) {
			prop.store(bw, comments);
		}
	}

	/**
	 * @author Mr.zyl
	 * @param key		键
	 * @param fileUrl	文件路径
	 * @param encode	编码格式
	 * @return			值
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	public static String findByKey(String key, String fileUrl, String encode)
			throws FileNotFoundException, IOException {
		Properties prop = new Properties();
		try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileUrl), "utf-8"))) {
			prop.load(br);
		}
		return prop.getProperty(key, null);
	}
}
